<?php


namespace app\api\common\member;

class Growth
{
	public static function set($user, $number, $type, $remarks, $source)
	{
		Finance::set($user, "growth", $number, $type, $remarks, $source);
		self::check_upgrade($user["id"]);
	}
	public static function check_upgrade($uid)
	{
		$user = $uid;
		if (!is_array($uid)) {
			$user = \think\Db::name("app_member_user")->where(["id" => $uid])->find();
		}
		$growth = $user["growth"];
		$current = \think\Db::name("app_member_user_level")->where(["id" => $user["level_id"], "appid" => $user["appid"]])->find();
		if ($current) {
			$current_sort = $current["level"] ?? 0;
			$lower = \think\Db::name("app_member_user_level")->where([["appid", "=", $user["appid"]], ["level", ">", $current_sort], ["upgrade", "=", "1"]])->order("level", "asc")->find();
			if ($lower) {
				if ($lower["integral"] <= $growth && $user["level_id"] != $lower["id"]) {
					Finance::set($user, "growth", $lower["integral"], 1, "会员等级升级到[{$lower["name"]}],使用{$lower["integral"]}点成长值", \app\common\model\MemberAppModel::UserGrowthLogSourceUpgradeExpend);
					\think\Db::name("app_member_user")->where(["id" => $user["id"]])->update(["level_id" => $lower["id"]]);
					$user = \think\Db::name("app_member_user")->where(["id" => $uid])->find();
					self::check_upgrade($user);
				}
			}
		}
		return $user;
	}
}